package com.hospital.diagnosis.module.config;

import com.hospital.common.utils.LogUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import static com.hospital.common.base.interfaces.Const.WEB_SOCKET_SESSION_PREFIX;

/**
 * Redis监听配置
 */
@Configuration
public class RedisListenerConfig {
    @Value("${chatbot.conclusion-prompt}")
    private String conclusionPrompt;

    @Autowired
    private ChatClient chatClient;

    @Bean
    public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory factory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        return container;
    }

    /**
     * 监听redis中ai会话过期的key,并进行后续处理
     */
    @Bean
    public KeyExpirationEventMessageListener keyExpirationListener(RedisMessageListenerContainer container) {
        return new KeyExpirationEventMessageListener(container) {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                String expiredKey = message.toString();
                if (expiredKey.startsWith(WEB_SOCKET_SESSION_PREFIX)) {
                    String sessionId = expiredKey.replace(WEB_SOCKET_SESSION_PREFIX, "");
                    LogUtils.info("会话:"+sessionId+"已过期");
                    // 调用 AI 持久化工具
                    persistSession(sessionId);
                }
            }
        };
    }

    private void persistSession(String conversationId) {
        chatClient.prompt()
                .advisors(spec -> spec
                        .param(ChatMemory.CONVERSATION_ID, conversationId))
                .user(conclusionPrompt)
                .call();
    }
}
